// tslint:disable
import { Component, Input, OnInit } from '@angular/core';
import { HttpService } from "src/app/shared/service/http.service";
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { AppGlobalService } from "src/app/shared/service/app-global.service";
import { ModalController, AlertController } from "@ionic/angular";
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { EventService } from 'src/app/shared/service/event.service';
@Component({
  selector: 'app-share-form-modal',
  templateUrl: './share-form-modal.component.html',
  styleUrls: ['./share-form-modal.component.scss'],
})
export class ShareFormModalComponent implements OnInit {
  shareData = {
    icon: "share.png",
    layout: "right",
    submit: {
      content: {},
      id: "string"
    }
  };
  title = '分享到58';
  subTitle = '请先完善信息，无58账号请先行注册';
  @Input() tagData: any;
  formGroup: FormGroup = new FormGroup({});
  allLabel: any = {};
  formTagData: any;
  submitBtn: any;
  open: boolean;
  time = -1;
  text = "获取验证码";
  constructor(
    private httpService: HttpService,
    private modalController: ModalController,
    private appGlobalService: AppGlobalService
  ) { }
  createFormGroup(tags) {
    try {
      for (let index = 0; index < tags.length; index++) {
        const element = tags[index];
        if (element.style === "tag.AppGeneralFormTagLogic") {
          this.formTagData = element;
          for (let i = 0; i < this.formTagData.data.htmlObj.length; i++) {
            const formItem = this.formTagData.data.htmlObj[i];
            this.addFormCtrl(formItem);
          }
        } else if (element.style === "countTipsTag") {
          this.subTitle = element.data.tips;
        } else if (element.style === "tag.AppGeneralButtonTagLogic") {
          this.submitBtn = element;
        }
      }
    } catch (error) {

    }
  }

  addFormCtrl(formItem) {
    const that = this;
    this.addFormControl(formItem);
  }

  inputClick(obj) {
  }

  addFormControl(formItem) {
    const that = this;
    if (formItem.formKey && formItem.formKey.length > 1 && !this.formGroup.controls[formItem.formKey]) {
      this.formGroup.addControl(formItem.formKey, new FormControl(formItem.value, that.validators(formItem)));
    }
    if (formItem.rules && formItem.rules.length > 0) {
      const message: any = {};
      formItem.rules.forEach(rule => {
        message[rule.name.toLowerCase()] = rule.message;
      });
      message.label = formItem.label;
      this.allLabel[formItem.formKey] = message;
    }
    if (formItem.formType === 'textInput' || formItem.formType === 'textInputLJ') {
      if (formItem.tags && formItem.tags.length > 0) {
        formItem.tags.forEach(e => {
          if (e.checked) {
            if (e.label.indexOf('自定义') > -1) {
              formItem.disabled = false;
            } else {
              formItem.disabled = true;
            }
            formItem.value = e.showValue;
            this.formGroup.patchValue({ [formItem.formKey]: e.showValue });
            this.formGroup.addControl(e.formKey, new FormControl(e.value));
          }
        });
      }
    }
  }

  submitForm() {
    if (this.formGroup.valid) {
      const params = this.formGroup.value;
      for (const prop in params) {
        if (Array.isArray(params[prop])) {
          params[prop] = params[prop].join(',');
        }
        if (prop === '') {
          // delete params[prop];
        }
      }
    } else {
      this.getErrors(this.formGroup);
      return;
    }
    const params = {
      content: {
        mobile: this.formGroup.get('account_thos__mobile').value,
        verification_code: this.formGroup.get('codebut').value,
        password: this.formGroup.get('account_thos_password').value,
        nickname: this.formGroup.get('account_thos_nickname').value,
        opportunity_id: this.submitBtn.data[0].submit.content.opportunity_id,
        onlyEvent: this.submitBtn.data[0].submit.content.onlyEvent
      },
      id: this.submitBtn.data[0].submit.id,
      sessionId: localStorage.getItem("sessionId")
    };
    this.httpService.delayShowLoading();
    this.httpService.post("application/submit", params, res => {
      if (res.success) {
        this.appGlobalService.showToast("发布成功", 3000, "middle");
        this.formGroup.reset();
        setTimeout(() => {
          this.modalController.dismiss();
        }, 2000);
      } else {
        this.appGlobalService.showToast(res.message, 1500, "middle");
      }
    });
  }
  ngOnInit() {
    if (this.tagData && this.tagData.tags) {
      this.createFormGroup(this.tagData.tags);
    }
  }
  closeClick() {
    this.formGroup.reset();
    this.modalController.dismiss();
  }
  validators(item) {
    const validators = [];
    if (item.rules && item.rules.length) {
      item.rules.forEach(rule => {
        if (rule.name === 'required' && rule.value === 'true') {
          validators.push(Validators.required);
        } else if (rule.name === 'minLength') {
          validators.push(Validators.minLength(Number(rule.value)));
        } else if (rule.name === 'maxLength') {
          validators.push(Validators.maxLength(Number(rule.value)));
        } else if (rule.name === 'min') {
          validators.push(Validators.min(Number(rule.value)));
        } else if (rule.name === 'max') {
          validators.push(Validators.max(Number(rule.value)));
        } else if (rule.name === 'pattern') {
          validators.push(Validators.pattern(rule.value));
        }
      });
    }
    return validators;
  }
  getErrors(form) {
    const errs = [];
    for (const name in form.controls) {
      if (form.controls[name].errors) {
        errs.push({ key: [name], err: form.controls[name].errors });
      }
    }
    if (errs.length) {
      const errItem = errs[0];
      const firstErrMsgKey = Object.keys(errItem.err)[0];
      console.log(errItem.key, '校验的字段名');
      const messageObj = this.allLabel[errItem.key];
      const showMessage = messageObj[firstErrMsgKey];
      this.appGlobalService.showToast(showMessage, 3000, 'top');
    }
  }
  getVC(invalid) {
    event.stopPropagation();
    console.log(this.formGroup.get("account_thos__mobile"));
    if (invalid) {
      this.appGlobalService.showToast("请输入正确手机号码", 3000, "top");
    } else {
      let submitId = '';
      let second = 60;
      this.formTagData.data.htmlObj.forEach(element => {
        if (element && element.formType === 'codebut') {
          submitId = element.submit.id;
          second = element.second;
          const params = {
            content: {
              mobile: this.formGroup.value.account_thos__mobile,
              onlyEvent: 'true'
            },
            id: submitId,
            sessionId: localStorage.getItem("sessionId")
          };
          this.httpService.post("application/submit", params, data => {
            if (data.success) {

              if (data.data && data.data.eventResult === "0") {
                this.appGlobalService.showToast(
                  "验证码已发送、请注意查收",
                  3000,
                  "top"
                );
              } else {
                this.appGlobalService.showToast(
                  data.data.eventResult,
                  5000,
                  "top"
                );
              }
            } else {
              this.appGlobalService.showToast(data.message, 3000, "top");
            }
            this.time = second;
            const timer = setInterval(() => {
              this.time = this.time - 1;
              if (this.time === -1) {
                clearInterval(timer);
                this.text = "获取验证码";
              }
            }, 1000);
          });
        }
      });
    }
  }
  formClick(e) {
    e.stopPropagation();
  }

}
